package modelfront

import (
	"freely/bin/comm"
	"freely/bin/crud"
	"freely/src/constant"

	types "freely/bin/customType"

	"gorm.io/gorm"
)

/**
 * 后台管理用户表结构
 * 也是所有用户
 * 用户只有一个角色和一个部门
 */
type FrontUserStu struct {
	crud.BaseModel
	Name         string            `gorm:"type:varchar(30)" json:"name" validate:"chinese"`                   // 真实姓名
	Username     string            `gorm:"type:varchar(80);unique" json:"username" validate:"required,stand"` // 用户账户
	Password     string            `gorm:"type:varchar(70)" json:"password,omitempty" validate:"required"`    // 用户登录密码
	NickName     string            `gorm:"type:varchar(40)" json:"nickName" validate:"stand"`                 // 昵称
	Avatar       string            `gorm:"type:varchar(255)" json:"avatar"`                                   // 用户头像
	Phone        string            `gorm:"type:varchar(15);unique" json:"phone"`                              // 用户手机号码
	Email        string            `gorm:"type:varchar(30);index:email" json:"email"`                         // 用户邮箱
	Birth        *types.CustomTime `gorm:"type:datetime;comment:" json:"birth"`                               // 出生日期
	RoleID       uint              `gorm:"index:role_id" json:"roleId"`                                       // 角色ID
	Role         *FrontRoleStu     `gorm:"-" json:"role,omitempty"`
	DepartmentID uint              `gorm:"index:dept_id" json:"departmentId"` // 所属部门
	Department   *FrontDeptStu     `gorm:"-" json:"department,omitempty"`
}

// 字段属性
var FrontUserCloumnTypeMap = map[string]string{
	"name":     crud.FiledLike,
	"username": crud.FiledLike,
	"nickName": crud.FiledLike,
	"phone":    crud.FiledLike,
	"email":    crud.FiledLike,
	"birth":    crud.FiledLess,
}

/**
 * 登录和注册时使用的结构体
 * 错误信息为配合多语言改为messageID
 */
type LoginParams struct {
	Username   string `json:"username" validate:"required" errInfo:"login.userNotNil"`
	Password   string `json:"password" validate:"required" errInfo:"login.passNotNil"`
	CaptchaId  string `json:"captchaId"`
	VerifyCode string `json:"verifyCode" errInfo:"login.captchaErr"`
}

var FrontUserName = "front_user"
var ModelName = "front"

func (m *FrontUserStu) TableName() string {
	return FrontUserName
}

func (m *FrontUserStu) GroupName() string {
	return ModelName
}

// 禁止注册admin和root用户
func (u *FrontUserStu) BeforeCreate(tx *gorm.DB) (err error) {
	if u.Username == "admin" || u.Username == "root" {
		return constant.ErrInvaild
	}
	return
}

// 禁止修改为admin和root用户
func (u *FrontUserStu) BeforeUpdate(tx *gorm.DB) (err error) {
	if u.Username == "admin" || u.Username == "root" {
		return constant.ErrInvaild
	}
	return
}

// 迁移用户表结构
func MigrateFrontUsers() {
	comm.MigrateTable(&FrontUserStu{})
}
